package com.ttg.security;

//~--- non-JDK imports --------------------------------------------------------

import com.ttg.utils.Assert;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.Charset;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

//~--- JDK imports ------------------------------------------------------------

//~--- classes ----------------------------------------------------------------

/**
 * Class KeystoreSignProvider
 * Description
 * Create 2016-02-25 01:05:39 
 * @author Ardy    
 */
public class KeystoreSignProvider implements SignProvider {

    /** 
     * Field x509Certificate
     * Description 
     */
    private final X509Certificate x509Certificate;

    /** 
     * Field privateKey
     * Description 
     */
    private final PrivateKey privateKey;

    /**
     * Constructs KeystoreSignProvider
     * Description
     *
     * @param kyeStoreType 类型：String
     * @param keyStorePath 类型：String
     * @param keyStorePassword 类型：char[]
     * @param alias 类型：String
     * @param keyPassword 类型：char[]
     *
     * @throws Exception 异常
     */
    public KeystoreSignProvider(String kyeStoreType, String keyStorePath, char[] keyStorePassword, String alias,
                                char[] keyPassword)
            throws Exception {
        Assert.hasText(keyStorePath, "客户端keystore路径不能为空");
        Assert.notNull(keyStorePassword, "keystore密码不能为空");
        this.x509Certificate = (X509Certificate) EncryptionUtils.getCertificate(kyeStoreType, keyStorePath,
                keyStorePassword, alias);
        this.privateKey = EncryptionUtils.getPrivateKeyByKeyStore(kyeStoreType, keyStorePath, keyStorePassword, alias,
                keyPassword);
    }

    /**
     * Method sign 
     * Description 说明：
     *
     * @param plaintext 说明：
     *
     * @return 返回值说明：
     *
     * @throws Exception 异常：
     */
    public String sign(byte[] plaintext) throws Exception {
        byte[] signatureInfo = EncryptionUtils.signByX509Certificate(plaintext, this.x509Certificate, this.privateKey);

        return Base64.encodeBase64String(signatureInfo);
    }

    public String sign(String plaintext ,Charset charset) throws Exception {
        return this.sign(plaintext.getBytes(charset));
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
